<template>
  <div class='order-page'>
    <div class="top-of-list">
      <div @click="gotoAddressList">
        <div class="have-address" v-if="showDefaultFlag">
          <img class="address-image" src="../../assets/defaultAddress.png"/>
          <div class="address-font">
            <div class="customer-info">
              <span class="customer-name">{{addressInfo.name}}</span>
              <span class="customer-phone">{{addressInfo.phone}}</span>
            </div>
            <div class="customer-address">
              {{addressInfo.address}}
            </div>
          </div>
          <div class="change-address">></div>
        </div>
        <div class="save-new-address" v-if="!showDefaultFlag">
          <img class="save-new-address-img" src="../../assets/addIcon.png"/>
          <span class="save-new-address-font">添加新地址</span>
        </div>
      </div>
      <img class="address-bottom" src="../../assets/tiao01.png"/>
    </div>
    <div class="order-info">
      <div v-for="(item,index) in productList" :key="index">
        <router-link :to="'/pages/goods/detail?id=' + item.productId" class="goods-info">
          <img class="goods-item-image" :src="item.picUrl"/>
          <div class="goods-item-info">
            <div class="goods-name">{{item.productName}}</div>
            <div class="goods-norms" v-if="item.propertiesName !== null && item.propertiesName.length !== 0 && item.propertiesName !== ''">{{item.propertiesName}}</div>
            <div style="height: 1.17rem" v-if="!(item.propertiesName !== null && item.propertiesName.length !== 0 && item.propertiesName !== '')"></div>
            <div class="goods-info-bottom">
              <div class="goods-info-left">
                <div class="goods-real-fee">
                  <div class="icon" v-if="orderType === '1'">￥</div>
                  {{item.productPrice}}
                  <div v-if="orderType === '0'">积分</div>
                </div>
              </div>
              <div class="goods-info-right">
                x{{item.productNumber}}
              </div>
            </div>
          </div>
        </router-link>
      </div>
    </div>
    <div class="delivery-type">
      <div class="delivery-type-title">配送方式</div>
      <div class="delivery-type-font" v-if="deliveryType === '1'">￥{{deliveryFee}}</div>
      <div class="delivery-type-font" v-if="deliveryType === '0'">快递包邮</div>
    </div>
    <div class="order-remark">
      <div class="order-remark-title">订单备注</div>
      <input type="text" maxlength="30" class="captcha-input" bindinput="inputRemark" placeholder="请输入备注信息"/>
    </div>
    <div class="goods-sum">
      <span class="goods-sum-num">共{{orderNum}}件商品 小计</span>
      <div class="goods-sum-fee"><span v-if="orderType === '1'">￥</span>{{goodsSumFee}}<span v-if="orderType === '0'">积分</span></div>
    </div>
    <div class="delivery-type">
      <div class="delivery-type-title">商品总额</div>
      <div class="delivery-type-font"><span v-if="orderType === '1'">￥</span>{{goodsSumFee}}<span v-if="orderType === '0'">积分</span></div>
    </div>
    <div class="delivery-type">
      <div class="delivery-type-title">总运费</div>
      <div class="delivery-type-font" v-if="deliveryType === '1' && deliveryFee !== null">￥{{deliveryFee}}</div>
      <div class="delivery-type-font" v-if="deliveryType === '0' || deliveryFee === null">￥0.00</div>
    </div>
    <div class="submit-order">
      <div class="order-fee-info">
        <span>合计</span>
        <span>{{submitFont}}</span>
      </div>
      <div class="submit" @click="submitOrder">提交订单</div>
    </div>
  </div>
</template>

<script>
import { API } from '../../config'
export default{
  data(){
    return {
      orderFrom: '0',   // 0 购物车 1 商品详情 2 拼团
      tpuId: '',
      showDefaultFlag: false,
      addressInfo: {
        addressId: '',
        name: '',
        phone: '',
        address: ''
      },
      orderInfo: [],
      productList: [],
      orderType: '1', // 0 积分 1 正常
      deliveryType: '1', // 0 包邮 1 快递
      deliveryFee: '',
      orderRemark: '',
      orderNum: 0,
      goodsSumFee: '',
      submitFont: '',
      shoppingCartIds: [],
      productSkuId: '',
      ids: '',
      addressId: '',
      btnStatus: true,
      num: ''
    }
  },
  methods:{
    gotoAddressList () {
      var url = '/user/addressList'
      if (this.ids !== '') {
        url = url + '?ids=' + this.ids
      } else if (this.productSkuId !== '') {
        url = url + '?productSkuId=' + this.productSkuId
        if (this.num !== '') {
          url = url + '&num=' + this.num
        }
        if (this.orderFrom === '2') {
          url = url + '&type=team'
          if (this.tpuId !== '') {
            url = url + '&tpuid=' + this.tpuId
          }
        }
      }
      this.$router.push({
        path: url
      })
    },
    submitOrder () {
      if (!this.btnStatus || this.addressInfo.addressId === '' || this.productList.length <= 0) {
        return
      }
      this.btnStatus = false
      var info = {}
      var productList = []
      info.addressId = this.addressInfo.addressId
      info.message = this.orderRemark
      this.productList.forEach(item => {
        productList.push({
          'productNumber': item.productNumber,
          'productSkuId': item.productSkuId,
          'shoppingCartId': this.orderFrom !== '0' ? null : item.shoppingCartId
        })
      })
      info.productList = productList
      info.tpuId = this.tpuId
      let accesstoken = this.getLocalStorage('accesstoken')
      this.$axios.post(API + '/order/submit',info,{
          headers: {'accesstoken': accesstoken}//设置header信息
        }).then((res)=>{
        if (res.data.code === 200) {
          this.shareAlbum(res.data.data.orderId)

        //   if (res.data.data.payMoney.length > 0) {
        //     this.$axios.post( API + '/order/gopay?orderId=' + res.data.data.orderId,{},{
        //   headers: {'accesstoken': accesstoken}//设置header信息
        // }).then((obj)=>{
        //       if (obj.data.code === 200) {
        //           // this.$message('支付。。')
        //           // let [err, result] = await pay(obj.data)
        //           // console.log(err)
        //           // if (result) {
        //           //   // 成功
        //           //   this.$message('支付成功')
        //           //   return wx.redirectTo({
        //           //     url: '/pages/shopping/paySuccess2?orderId=' + res.data.data.orderId
        //           //   })
        //           // }
        //           this.shareAlbum(res.data.data.orderId)
        //         }
        //         // todo 弹框
        //         // console.log('支付失败' + res.data.data.payMoney + '元')
        //         this.$message('申请支付失败')
        //         return this.$router.push({
        //           path: '/order/orderDetail?id=' + res.data.data.orderId
        //         })
        //     })
          }
        // } else if (res.data.code === 20006) {
        //   this.$message('商品已下架')
        // } else if (res.data.code === 30006) {
        //   this.$message('库存不足')
        // } else if (res.data.code === 10003){
        //   this.$message('请填写收货地址')
        // }else {
        //   this.$message('下单失败')
        // }
        this.btnStatus = true
      })
    },
    init () {
      if (this.num === '' || this.num === undefined) {
        this.num = '1'
      }
      let accesstoken = this.getLocalStorage('accesstoken')
      if(this.orderFrom === '0'){
        this.$axios.post( API + '/shoppingcart/gosettle',{'shoppingCartIds': this.shoppingCartIds},{
          headers: {'accesstoken': accesstoken}//设置header信息
        }).then((res)=>{
          this.resDeal(res.data)   
        })
      }else if(this.orderFrom === '2'){
        this.$axios.post( API + '/product/openOrJoinGroupBuyActive',{'productSkuId': this.productSkuId, 'tpuId': this.tpuId},{
          headers: {'accesstoken': accesstoken}//设置header信息
        }).then((res)=>{
          this.resDeal(res.data)
        })
      }else{
        this.$axios.post( API + '/product/nowbuy?',{'productSkuId':this.productSkuId,'productNumber': parseInt(this.num)},{
          headers: {'accesstoken': accesstoken}//设置header信息
        }).then((res)=>{
          this.resDeal(res.data)
        })
      }
    },
    resDeal(res){
      if (res.code === 200) {
        // 暂时都是正常下单，不考虑积分
        this.deliveryFee = res.data.totalFreight
        this.goodsSumFee = res.data.totalMoney
        this.productList = res.data.productList
        if (this.orderFrom === '2') {
          this.tpuId = res.data.tpuId
        }
        if (this.addressId !== '') {
          this.$axios.get( API + '/receivinggoodsaddress/detail?id=' + this.addressId).then((resp)=>{
            if (resp.code === 200) {
              this.addressInfo.addressId = resp.data.id
              this.addressInfo.address = resp.data.provinceCityAreaName + resp.data.addressDetail
              this.addressInfo.name = resp.data.receivingGoodsName
              this.addressInfo.phone = resp.data.tel
              this.showDefaultFlag = this.addressInfo.addressId
            }
          })
        } else {
          this.addressInfo.address = res.data.address
          this.addressInfo.phone = res.data.tel
          this.addressInfo.name = res.data.receivingGoodsName
          this.addressInfo.addressId = res.data.addressId
          this.showDefaultFlag = this.addressInfo.addressId
        }
      } else if (res.code === 30007) {
        this.$message('只能购买一件秒杀商品')
        setTimeout(function () {
          this.$router.push({
            path: '/'
          })
        }, 1500)
        return
      } else if (res.code === 30006) {
        this.$message('库存不足')
        setTimeout(function () {
          this.$router.push({
            path: '/'
          })
        }, 1500)
        return
      }else {
        this.$message(res.msg)
      }
      var fee = 0
      this.productList.forEach(item => {
        this.orderNum = this.orderNum + item.productNumber
      })
      fee = parseFloat(this.goodsSumFee || 0) + parseFloat(this.deliveryFee || 0)
      this.submitFont = '￥' + fee.toFixed(2) + '元'
    },
    // 支付
    shareAlbum(orderId) {
        let params = {};
        let url = 'wechatPay：//orderId=' + orderId;//URL Scheme 安卓小伙伴提供
        this.shareJump(url, params);
    },
    // 分享跳转
    shareJump(url, param) {
        // 判断是否是微信
        var is_weixin = (function () { return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1 })();
        if (is_weixin) {
            // 微信则跳转下载页
            window.location.href = "https://www.pgyer.com/Q8AS?sig=Myi3vdBmKRpads5BP6VZd%2FHbxfG%2Bfm6mcEwZZM3SK3Y5o%2FS7QZ%2B%2BI6SJ3%2BdQNAmT"
            return;
        }
        // 非微信拼接参数
        let params = param
        let urls = url;
        let first = true;
        if (params) {
            for (let i in params) {
                if (first) {
                    urls += "?"
                    first = false;
                } else {
                    urls += "&"
                }
                urls += i + "=" + params[i]
            }
        }
        // 安卓端跳转
        var iFrame;
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        // console.log("isAndroid", isAndroid, isiOS);
        if (isAndroid) {
            //安卓终端使用iframe
            iFrame = document.createElement("iframe");
            iFrame.setAttribute("src", urls);
            iFrame.setAttribute("style", "display:none;");
            iFrame.setAttribute("height", "0px");
            iFrame.setAttribute("width", "0px");
            iFrame.setAttribute("frameborder", "0");
            document.body.appendChild(iFrame);
            // 发起请求后这个 iFrame 就没用了，所以把它从 dom 上移除掉
            iFrame.parentNode.removeChild(iFrame);
            iFrame = null;
            // 如果用户没有安装APP，则提示用户去安装APP
            setTimeout(() => {
                window.location.href = "https://www.pgyer.com/Q8AS?sig=Myi3vdBmKRpads5BP6VZd%2FHbxfG%2Bfm6mcEwZZM3SK3Y5o%2FS7QZ%2B%2BI6SJ3%2BdQNAmT"; // 这里可以自行写一个延时关闭的弹窗，也可以跳转至app下载地址
            }, 2000);
        } else if (isiOS) {
            //iOS终端直接页面跳转
            window.location.href = urls;
            // 如果用户没有安装APP，则提示用户去安装APP
            setTimeout(() => {
                window.location.href = "https://www.pgyer.com/Q8AS?sig=Myi3vdBmKRpads5BP6VZd%2FHbxfG%2Bfm6mcEwZZM3SK3Y5o%2FS7QZ%2B%2BI6SJ3%2BdQNAmT"; // 这里可以自行写一个延时关闭的弹窗，也可以跳转至app下载地址
            }, 2000);
        } else {
            window.location.href = urls;
        }
      // window.location.href = urls;
    }
  },
  mounted() {
    let options = this.$route.query
    if (options.shoppingCarIds) {
      this.orderFrom = '0'
      var ids = options.shoppingCarIds
      this.ids = options.shoppingCarIds
      if (options.addressId) {
        this.addressId = options.addressId
      }
      var idList = ids.split(',')
      idList.forEach(item => {
        this.shoppingCartIds.push(parseInt(item))
      })
    } else if (options.type) {
      if (options.type === 'team') {
        this.orderFrom = '2'
        this.productSkuId = options.productSkuId
        this.tpuId = options.tpuid
        if (options.addressId) {
          this.addressId = options.addressId
        }
      }
    } else {
      this.orderFrom = '1'
      this.productSkuId = options.productSkuId
      if (options.num) {
        this.num = options.num
      }
      if (options.addressId) {
        this.addressId = options.addressId
      }
    }
    this.init()
  }
}
</script>

<style lang='less' scoped>
@import '../../css/common.less';
@import '../../css/order/order.less';
</style>
